﻿using Models.ApiModel;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BLL;
using System.Web;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Models.webReq;
using SqlSugar;
using System.Configuration;
using Models.ApiModel.req;
using WHC.Framework.Commons;
using Tools;

namespace webui.Controllers
{
    public class ApiTraderController : ApiController
    {
        TraderInfoBLL trBll = new TraderInfoBLL();
        Car_imgBLL carimgBLL = new Car_imgBLL();
        UserInfoBLL userbll = new UserInfoBLL();
        string host = ConfigurationSettings.AppSettings["httpip"];

        //新增
       // [VerifyKeyAttribute]
        public BaseRes AddCar(TraderInfo car)
        {
            BaseRes res = new BaseRes();
            res.Code = 0;
            if (string.IsNullOrEmpty(car.coinName))
            {
                res.Msg = "名不能为空";
                return res;
            }

            if (car.buyPrice == 0)
            {
                res.Msg = "买入价格不能为空";
                return res;
            }
            if (car.Carimgs.Length < 1)
            {
                res.Msg = "请上传图片";
                return res;
            }
            string userstr = Base64Util.Decrypt(car.Token);
            Token user = userstr.ToObject<Token>();
            car.firstImg = car.Carimgs[0];
            car.createtime = DateTime.Now;

            car.CreateUserID = user.Userid;
            int carid = trBll.InsertReturnIdentity(car); //得到主键id
            Car_img[] imgarr = new Car_img[car.Carimgs.Length];
            for (int i = 0; i < car.Carimgs.Length; i++)
            {
                Car_img img = new Car_img { Imgurl = car.Carimgs[i] };
                img.carinfoId = carid;
                imgarr[i] = img;
                img.isfirst = i == 0 ? true : false;
            }
            carimgBLL.InsertRange(imgarr);
            res.Code = 1;
            res.Msg = "成功";
            return res;
        }



        public BaseRes UpLoadImg()
        {
            BaseRes res = new BaseRes();

            HttpPostedFile file = HttpContext.Current.Request.Files["file"];//接收
            string ext = Path.GetExtension(file.FileName);//文件后缀名
            string[] LimitPictureType = new string[] { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" };
            if (LimitPictureType.Contains(ext.ToUpper()))
            {
                try
                {
                    string _newFileName = Guid.NewGuid().ToString();
                    string _dbPicturePath = "AppUpImg/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                    string _toServerPicturePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _dbPicturePath);
                    string imgfullname = _toServerPicturePath + _newFileName + ext;
                    res.Data = _dbPicturePath + _newFileName + ext; //保存数据库的
                    if (!Directory.Exists(_toServerPicturePath))
                    {
                        Directory.CreateDirectory(_toServerPicturePath);
                    }
                    file.SaveAs(imgfullname);
                    res.Code = 1;
                }
                catch (Exception ce)
                {
                    res.Code = 0;
                    res.Msg = ce.Message;
                    Tools.CommonHellper.WriteLog(ce.Message + ce.StackTrace);
                }

            }
            else
            {
                res.Code = 0;
                res.Msg = "图片格式不对";
            }

            return res;
        }


        //查询车辆集合
        [HttpPost]
        public BaseRes QueryCarList(TrCondition carcondtion)
        {
            BaseRes res = new BaseRes();

            if (carcondtion.PageSize == 0)
            {
                carcondtion.PageSize = 10;
            }
            if (carcondtion.PageIndex == 0)
            {
                carcondtion.PageIndex = 1;
            }
            PageModel pg = new PageModel() { PageIndex = carcondtion.PageIndex, PageSize = carcondtion.PageSize };
            List<TraderInfo> list = new List<TraderInfo>();
            List<IConditionalModel> liswhere = new List<IConditionalModel>();

            if (!string.IsNullOrEmpty(carcondtion.keyword))
            {
                liswhere.Add(new ConditionalCollections()
                {
                    ConditionalList =
                    new List<KeyValuePair<WhereType, SqlSugar.ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>
                        ( WhereType.And ,
                        new ConditionalModel() { FieldName = "titleName", ConditionalType = ConditionalType.Like, FieldValue = carcondtion.keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>
                        (WhereType.Or,
                        new ConditionalModel() { FieldName = "coinName", ConditionalType = ConditionalType.Like, FieldValue = carcondtion.keyword })
                    }
                });
            }


            list = trBll.GetPageList(liswhere, pg, s => s.id, OrderByType.Desc);
            for (int i = 0; i < list.Count; i++)
            {
                list[i].firstImg = host + list[i].firstImg;

            }
            var result = new { count = pg.PageCount, data = list };
            res.Code = 1;
            res.Data = result;
            return res;
        }

        //获取一个模型
        [HttpPost]
        public BaseRes GetCarByid(ReqCar req)
        {
            BaseRes res = new BaseRes();
            if (req != null && req.ID > 0)
            {
                TraderInfo car = trBll.GetById(req.ID);
                if (car != null)
                {
                    //查询图片
                    List<Car_img> imglist = carimgBLL.GetList(u => u.carinfoId == req.ID).OrderByDescending(s => s.isfirst).ToList();
                    car.Carimgs = new string[imglist.Count];

                    string userstr = Base64Util.Decrypt(req.Token);
                    Token user = userstr.ToObject<Token>();

                    for (int i = 0; i < imglist.Count; i++)
                    {
                        car.Carimgs[i] = host + imglist[i].Imgurl;
                    }
                    res.Data = car;
                    res.Msg = "查询成功";
                }
                else
                {
                    res.Code = 0;
                    res.Msg = "ID错误";
                }
            }
            else
            {
                res.Code = 0;
                res.Msg = "ID错误";
            }
            return res;

        }

        //获取一个用户的 
        [HttpPost]
        public BaseRes GetCarByUserID(CarCondition carcondtion)
        {
            BaseRes res = new BaseRes();
            if (carcondtion.PageSize == 0)
            {
                carcondtion.PageSize = 10;
            }
            if (carcondtion.PageIndex == 0)
            {
                carcondtion.PageIndex = 1;
            }
            PageModel pg = new PageModel() { PageIndex = carcondtion.PageIndex, PageSize = carcondtion.PageSize };

            string userstr = Base64Util.Decrypt(carcondtion.Token);
            Token user = userstr.ToObject<Token>();
            if (user == null)
            {
                res.Code = 0;
                res.Msg = "没有权限";
                return res;
            }

            List<TraderInfo> list = new List<TraderInfo>();
            if (string.IsNullOrEmpty(carcondtion.keyword))
            {
                List<IConditionalModel> liswhere = new List<IConditionalModel>();
                liswhere.Add(new ConditionalModel() { FieldName = "sellState", ConditionalType = ConditionalType.NoEqual, FieldValue = "0" });
                liswhere.Add(new ConditionalModel() { FieldName = "CreateUserID", ConditionalType = ConditionalType.Equal, FieldValue = user.Userid.ToString() });
                list = trBll.GetPageList(liswhere, pg, s => s.id, OrderByType.Desc);
            }
            else
            {
                list = trBll.GetPageList(u => u.CreateUserID == user.Userid, pg, s => s.id, OrderByType.Desc);
            }

            for (int i = 0; i < list.Count; i++)
            {
                list[i].firstImg = host + list[i].firstImg;
            }
            var result = new { count = pg.PageCount, data = list };
            res.Code = 1;
            res.Data = result;
            return res;
        }

        //修改一信息
     //   [VerifyKeyAttribute]
        public BaseRes EditCar(TraderInfo trmodel)
        {
            BaseRes res = new BaseRes();
            res.Code = 0;
            if (string.IsNullOrEmpty(trmodel.coinName))
            {
                res.Msg = "名不能为空";
                return res;
            }

            if (trmodel.buyPrice == 0)
            {
                res.Msg = "买入价格不能为空";
                return res;
            }
            if (trmodel.Carimgs.Length < 1)
            {
                res.Msg = "请上传图片";
                return res;
            }
            if (trmodel.Carimgs.Length < 1)
            {
                res.Msg = "请上传图片";
                return res;
            }
            TraderInfo dbcar = trBll.GetById(trmodel.id);
            string userstr = Base64Util.Decrypt(trmodel.Token);
            Token user = userstr.ToObject<Token>();


            Car_img[] imgarr = new Car_img[trmodel.Carimgs.Length];
            for (int i = 0; i < trmodel.Carimgs.Length; i++)
            {
                if (trmodel.Carimgs[i].Contains(host))
                {
                    trmodel.Carimgs[i] = trmodel.Carimgs[i].Replace(host, ""); //删掉HTTP。
                }
                Car_img img = new Car_img { Imgurl = trmodel.Carimgs[i] };
                img.carinfoId = dbcar.id;
                imgarr[i] = img;
                img.isfirst = i == 0 ? true : false;
            }
            dbcar.firstImg = trmodel.Carimgs[0];
            dbcar.titleName = trmodel.titleName == null ? "" : trmodel.titleName;
            dbcar.coinName = trmodel.coinName == null ? "" : trmodel.coinName;
            dbcar.allProperty = trmodel.allProperty == null ? 0 : trmodel.allProperty;
            dbcar.buyPrice = trmodel.buyPrice == null ? 0 : trmodel.buyPrice;
            dbcar.stopLossPrice = trmodel.stopLossPrice == null ? 0 : trmodel.stopLossPrice;
            dbcar.sellPrice = trmodel.sellPrice == null ? 0 : trmodel.sellPrice;
            dbcar.isBuy = trmodel.isBuy == null ? 0 : trmodel.isBuy;
            dbcar.buyNum = trmodel.buyNum == null ? 0 : trmodel.buyNum;
            dbcar.destPrice = trmodel.destPrice == null ? 0 : trmodel.destPrice;
            dbcar.buyReason = trmodel.buyReason == null ? "" : trmodel.buyReason;
            dbcar.firstImg = trmodel.firstImg == null ? "" : trmodel.firstImg;
            dbcar.ALLadjust = trmodel.ALLadjust == null ? "" : trmodel.ALLadjust;
            dbcar.profit = trmodel.profit == null ? 0 : trmodel.profit;
            dbcar.ModifyUserID = user.Userid;
            dbcar.CloseTime = trmodel.CloseTime;
            dbcar.Sumup = trmodel.Sumup;
            dbcar.ykb = trmodel.ykb;
            dbcar.Modifytime = DateTime.Now; 
            trBll.Update(dbcar);
            carimgBLL.Delete(s => s.carinfoId == trmodel.id);
            carimgBLL.InsertRange(imgarr);
            res.Code = 1;
            res.Msg = "修改成功";


            return res;
        }



        //删除
        [VerifyKeyAttribute]
        public BaseRes Del(TraderInfo car)
        {
            BaseRes res = new BaseRes();
            res.Code = 0;
            if (car.id == 0)
            {
                res.Msg = "ID不能为空";
                return res;
            }
            TraderInfo dbcar = trBll.GetById(car.id);
            string userstr = Base64Util.Decrypt(car.Token);
            Token user = userstr.ToObject<Token>();
            trBll.Delete(dbcar);
            res.Code = 1;
            res.Msg = "删除成功";

            return res;
        }





        [VerifyKeyAttribute]
        public string Gets2(string sf)
        {
            //http://localhost:23586/api/apicar/gets2?sf=sdfs
            return sf + "f车";
        }

        public string Gets()
        {
            return "测试ktrsahg";
        }


    }
}
